<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <script src="./js/link.js"></script>
    <script src="./js/docx/docx.umd.js"></script>
    <script src="./js/docx/FileSaver.js"></script>
    <script src="./js/docx/docGenerator.js"></script>
</head>
<body>
    <div class="wrap">
        <div id="sidebar">
            <h1><a href="./">TangYuan</a></h1>
            <img src="./img/nav.png" width="30" height="30" onclick="onLinkToggleDisplay()" id="navimg">
            <div id="nav">
                <h2>目录</h2>
                <ul id="list"></ul>
                <h2>手机扫码访问</h2>
                <img src="img/addr.png" alt="手机扫码访问" width="125" height="125">
                <h2>微信公众号</h2>
                <img src="img/gzh.bmp" alt="微信公众号" width="120" height="120">
                <p>杨奉全</p>
                <p>邮箱： <a href="mailto:yangfengquan@126.com">yangfengquan@126.com</a></p>
				<p><a href="sitemap.html">网站地图</a></p>
                <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
                <p style="font-size: 14px; color: #ccc;"><span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span></p>
            </div> 
        </div>
        <div id="main">
		    <p id="waiting" class="warning">页面正在加载...</p>
            <h1 id="main-title"></h1>
            <div id="form"></div>
            <p id="warning" class="warning"></p>
            <p id="btn" style="display:none;">
                <button onclick="calc()">运算</button>
                <button onclick="doc()">计算书</button>
            </p>
            <h2 id="res-title" style="display:none;">结果：</h2>
            <div id="result"></div>
        </div> 
    </div>
    <script type="module">
        import * as unit from "./js/unitConverter.js"
        import Fm from "./js/fm.js";
        import db from "./js/data.js";
		
		//网页加载完成后，隐藏等待提示，并显示隐藏内容。
		window.onload = () => { 
			document.getElementById("waiting").style.display = "none";
			document.getElementById("btn").style.display = "block";
			document.getElementById("res-title").style.display = "block";
		}
        const urlSearchParams = new URLSearchParams(window.location.search);
        let url_fm = urlSearchParams.get('fm');

        (function () {    
            createLinkEle(db);
            if (url_fm != '' && url_fm != null) {
                document.title = db[url_fm].text;

                document.getElementById("main-title").innerText = db[url_fm].text;
                let formEle = document.getElementById("form");
                createFormEle(db[url_fm].form, formEle);
                let resultEle = document.getElementById("result");
                createFormEle(db[url_fm].result, resultEle);
                if (document.getElementsByClassName("br").length > 0) {
                    document.getElementsByClassName("br")[0].parentNode.insertBefore(
                        document.createElement("br"),
                        document.getElementsByClassName("br")[0]);
                }
            } else {
                window.location.href='./';
            }
            if (window.screen.width <= 600) {
                document.getElementById('nav').style.display = 'none'
            }
        })();
        
        function createFormEle(data, ele){
            data.forEach(item => {
                switch (item.tag) {
                    case 'input':
                        ele.appendChild(createInputEle(item));
                        break;
                    case 'select':
                        ele.appendChild(createSelectEle(item));
                    default:
                        break;
                }
            });
        }

        function createInputEle(inp) {
            let groupEle = document.createElement('div')
            groupEle.className = inp.pclass
            let labelEle = document.createElement('label')
            labelEle.innerText = inp.name
            labelEle.setAttribute('for', inp.id)
            groupEle.appendChild(labelEle)
        
            let inputEle = document.createElement('input')
            inputEle.setAttribute('name', inp.id)
            inputEle.setAttribute('id', inp.id)
            inputEle.setAttribute('autocomplete', 'on')
            inputEle.type = inp.type
            inputEle.value = inp.value
            if (inp.placeholder) {
                inputEle.placeholder = inp.placeholder
            }
            inputEle.required = inp.required
            inputEle.readOnly = inp.readonly
            inputEle.className = inp.class
            groupEle.appendChild(inputEle)
            if (inp.hasOwnProperty("datalist")) {
                inputEle.setAttribute("list", inp.id + "-datalist");
                let datalistEle = document.createElement("datalist");
                datalistEle.id = inp.id + "-datalist"
                inp.datalist.forEach(v => {
                    datalistEle.appendChild(new Option(v));
                });
                groupEle.appendChild(datalistEle);
            }
            
        
            if (inp.hasOwnProperty("unitset")) {
                groupEle.appendChild(createUnitSelect(inp.id, inp.unitset, inp.unit));
            }

            if (inp.other != '' && inp.hasOwnProperty("other")) {
                let spanEle = document.createElement('span');
                spanEle.innerText = inp.other;
                groupEle.appendChild(spanEle);
            }
            return groupEle
        }

        function createSelectEle(sel) {
            let groupEle = document.createElement('div');
            groupEle.className = sel.pclass;
            let labelEle = document.createElement('label');
            labelEle.innerText = sel.name;
            labelEle.setAttribute('for', sel.id);
            groupEle.appendChild(labelEle);
        
            let selectEle = document.createElement('select');
            selectEle.setAttribute('name', sel.id);
            selectEle.setAttribute('id', sel.id);
            selectEle.setAttribute('autocomplete', 'on');
            selectEle.required = sel.required
            selectEle.readOnly = sel.readonly
            selectEle.setAttribute('onchange', sel.listener);
            sel.opts.forEach(opt => {
                selectEle.add(new Option(opt.text, opt.value));
            });
            selectEle.value = sel.value;
            groupEle.appendChild(selectEle);
        
            if (sel.unit != '' && sel.hasOwnProperty("unit")) {
                let spanEle = document.createElement('span');
                spanEle.innerText = sel.unit;
                groupEle.appendChild(spanEle);
            }

            if (sel.other != '' && sel.hasOwnProperty("other")) {
                let spanEle = document.createElement('span');
                spanEle.innerText = sel.other;
                groupEle.appendChild(spanEle);
            }
            
            return groupEle;
        }
        function createUnitSelect(id, unitsetName, selected) {
            let unitset = {}
            if (unitsetName === "*") {//unitConverter缺少的单位集合
                unitset[selected] = '';//将当前“单位”添加至单位集合
            } else {
                unitset = unit[unitsetName];
            }

            let selectEle = document.createElement("select");
            selectEle.setAttribute('id', id + "-unit");
            selectEle.className = "unit";

            Object.keys(unitset).forEach(unit => {
                selectEle.add(new Option(unit, unit));
            });

            selectEle.value = selected;
            selectEle.setAttribute("data-last-val", selected);

            selectEle.addEventListener("change", function () {
                let lastUnit = this.dataset.lastVal;
                this.dataset.lastVal = this.value;
                let curUnit = this.value;

                let lastValue = document.getElementById(id).value;
                if (lastValue) {
                    document.getElementById(id).value = unit.default(lastValue, lastUnit, curUnit);
                }
            });
            
            return selectEle;
        }
        function inputForm() {
            let form = [];
            for (let i = 0; i < db[url_fm].form.length; i++) {
                if (db[url_fm].form[i].required && !document.getElementById(db[url_fm].form[i].id).value) {
                    return db[url_fm].form[i].name;
                }
                form.push({
                    id: db[url_fm].form[i].id,
                    value: document.getElementById(db[url_fm].form[i].id).value,
                    unit: document.getElementById(db[url_fm].form[i].id + "-unit") ? document.getElementById(db[url_fm].form[i].id + "-unit").value : ''
                })
            }
            return form;
        }
        function resultForm() {
            let result = [];
            db[url_fm].result.forEach(item => {
                result.push({
                    id: item.id,
                    value: '',
                    unit: document.getElementById(item.id + "-unit") ? document.getElementById(item.id + "-unit").value : ''
                });
            });
            return result;
        }
        function showResult(result) {console.log(result);
            result.forEach(item => {
                document.getElementById(item.id).value = item.value;
            });
        }
        window.calc = function() {
            if (!Array.isArray(inputForm())) {
                document.getElementById("warning").innerText = "警告：“" + inputForm() + "” 未正确填写！" ;
                document.getElementById("warning").style.display = "block";
            } else {
                document.getElementById("warning").style.display = "none";
                let fm = new Fm(inputForm(), resultForm());
                fm[url_fm]();
                showResult(fm._result);
            }
        }
        window.doc = () => {
            if (!Array.isArray(inputForm())) {
                document.getElementById("warning").innerText = "警告：“" + inputForm() + "” 未正确填写！" ;
                document.getElementById("warning").style.display = "block";
            } else {
                document.getElementById("warning").style.display = "none";
                
                let fm = new Fm(inputForm(), resultForm());
                fm[url_fm]();
                
                let form = [...fm._form], result = [...fm._result];
                form.forEach(item => {
                    for (let i = 0; i < db[url_fm].form.length; i++) {
                        if (item.id === db[url_fm].form[i].id) {
                            item.name = db[url_fm].form[i].name;
                        }
                    }
                });
                result.forEach(item => {
                    for (let i = 0; i < db[url_fm].result.length; i++) {
                        if (item.id === db[url_fm].result[i].id) {
                            item.name = db[url_fm].result[i].name;
                        }
                    }
                });
                if (url_fm === "waterProps" || url_fm === "pureProps") {
                    form.splice(1, 1);
                    form.splice(2, 1);
                    form[1].name = propObj[fm._form[1].value].name;
                    form[2].name = propObj[fm._form[3].value].name;
                }

                if (url_fm === "pipeHInsultion" || url_fm === "pipeCInsultion" || url_fm === "waterPipe") {
                    let i = 0;
                    for (; i < form.length; i++) {
                        if (form[i].name === "导热系数 λ=") {
                            break;
                        }
                    }
                    form[i].name = "导热系数";
                    form[i].value = "λ=" + form[i].value + form[i].other;
                    for (let j = i + 1; j < i + 7; j++) {
                        form[i].value = form[i].value + form[j].value + form[j].other;
                    }
                    form.splice(i + 1, 6);
                }

                doc_generate(db[url_fm].text, form, result);
            }         
        }

        var propObj = {
            T:   {name: "温度",         unit: "C",        unitset: "temperature_unit"},
            p:   {name: "压力",         unit: "MPaA",     unitset: "pressure_unit"},
            h:   {name: "质量比焓",         unit: "kJ/kg",    unitset: "*"},
            v:   {name: "质量比体积",       unit: "m3/kg",    unitset: "specificVolume_unit"},
            rho: {name: "质量密度",         unit: "kg/m3",    unitset: "density_unit"},
            s:   {name: "质量比熵",         unit: "kJ/(kg.K)",    unitset: "*"},
            u:   {name: "质量内能",         unit: "kJ/kg",    unitset: "*"},
            Cp:  {name: "定压比热容",   unit: "kJ/(kg·K)", unitset: "*"},
            Cv:  {name: "定容比热容",   unit: "kJ/(kg·K)", unitset: "*"},
            w:   {name: "声速",         unit: "m/s",      unitset: "speed_unit"},
            my:  {name: "动力粘度",     unit: "Pa·s",     unitset: "*"},
            tc:  {name: "导热系数",     unit: "W/(m·K)",  unitset: "*"},
            st:  {name: "表面张力",     unit: "N/m",      unitset: "*"},
            x:   {name: "干度",         unit: "",},
            vx:  {name: "气态体积分数", unit: "",}
        }
        propObj["P"] = propObj.p;
        propObj["DMOLAR"] = {name: "摩尔密度", unit: "mol/m3", unitset: "*"};
        propObj["D"] = propObj.rho;
        propObj["HMOLAR"] = {name: "摩尔比焓", unit: "J/mol", unitset: "*"};
        propObj["H"] = {name: "摩尔比焓", unit: "J/kg", unitset: "*"};;
        propObj["SMOLAR"] = {name: "摩尔比熵", unit: "J/(mol.K)", unitset: "*"};
        propObj["S"] = {name: "质量比熵", unit: "J/(kg.K)", unitset: "*"};
        propObj["UMOLAR"] = {name: "摩尔内能", unit: "J/mol", unitset: "*"};
        propObj["U"] = {name: "质量内能", unit: "J/kg", unitset: "*"};
        propObj["Q"] = {name: "气体比率", unit: "mol/mol", unitset: "*"};
        const modes = [
                ['p','T'],
                ['p','h'],
                ['p','s'],
                ['p','rho'],
                ['p','x'],
                ['T','x'],
                ['h','s'],
                ['h','rho']
            ]
        const coolModes = ["P","T","DMOLAR", "D", "HMOLAR", "H","SMOLAR","S","UMOLAR","U","Q",];
        window.onPropArg1Change = function() {
            let arg1 = document.getElementById('propArg1').value;

            let arg2_ele = document.getElementById("propArg2");
            arg2_ele.innerHTML = "";

            if (url_fm === "pureProps") {
                let arg2s = coolModes.filter(v => v != arg1);
                arg2s.forEach(v => {
                    arg2_ele.options.add(new Option(propObj[v].name, v));
                }); 
            } else {
                modes.forEach(item => {
                if (item[0] == arg1) {
                    arg2_ele.options.add(new Option(propObj[item[1]].name, item[1]));
                }
            });
            }
            

            if (document.getElementById('propValue1-unit')) {
                document.getElementById('propValue1-unit').remove();
            }
            if (document.getElementById('propValue2-unit')) {
                document.getElementById('propValue2-unit').remove();
            }
            if (propObj[arg1].unitset) {
                document.getElementById('propValue1').parentNode.appendChild(createUnitSelect("propValue1", propObj[arg1].unitset, propObj[arg1].unit))
            }
            if (propObj[arg2_ele.value].unitset) {
                document.getElementById('propValue2').parentNode.appendChild(createUnitSelect("propValue2", propObj[arg2_ele.value].unitset, propObj[arg2_ele.value].unit))
            }
        }
        window.onPropArg2Change = function() {
            let arg2_ele = document.getElementById("propArg2");
            if (document.getElementById('propValue2-unit')) {
                document.getElementById('propValue2-unit').remove();
            }
            if (propObj[arg2_ele.value].unitset) {
                document.getElementById('propValue2').parentNode.appendChild(createUnitSelect("propValue2", propObj[arg2_ele.value].unitset, propObj[arg2_ele.value].unit))
            }
        }
    </script>
</body>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  if (window.location.hostname == "yangshu.gitee.io") {
    hm.src = "https://hm.baidu.com/hm.js?f21a3bcbd68f3fda366faacbd5cb7c4d";
  } 
  if (window.location.hostname == "yangfengquan.github.io") {
    hm.src = "https://hm.baidu.com/hm.js?c601c0ade979f55c4e2d64e5eb0eac59";
  }
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>
<script src="./js/coolprop.js"></script>
</html>